<template>
  <view class="statistics">
    <view class="sta-header">
      <text>工作量统计</text>
      <button :class="{ 'active': activeButton === 'year' }" class="time-button" @click="fetchYearData">本年</button>
      <button :class="{ 'active': activeButton === 'month' }" class="time-button" @click="fetchMonthData">本月</button>
      <button :class="{ 'active': activeButton === 'week' }" class="time-button" @click="fetchWeekData">本周</button>
      <button :class="{ 'active': activeButton === 'day' }" class="time-button" @click="fetchDayData">本日</button>
      <view class="date-header">
      <uni-datetime-picker
                type="daterange"
                v-model="dateRange"
                :start="defaultStartDate"
                :end="defaultEndDate"
                rangeSeparator="至"
                @change="onDateRangeChange"
              />
      </view>

    </view>
    <view class="list-container">
      <scroll-view class="Statistic-list" scroll-y :show-scrollbar="false">
       <view  v-for="(row, rowIndex) in dividedStatisticList" :key="rowIndex">
        <view class="Statistic-item" v-for="(StatisticItem, itemIndex) in row" :key="itemIndex" @tap="toDetail(StatisticItem)">
          <view class="list-name Statistic-text">
            <text>{{ StatisticItem.name }}管理</text>
          </view>
          <view class="Statistic-text text-style">
            <text>建档人数</text>
            <text>{{ StatisticItem.dNum }}</text>
          </view>
          <view class="Statistic-text text-style">
            <text>签约人数</text>
            <text>{{ StatisticItem.signnum }}</text>
          </view>
          <view class="Statistic-text text-style">
            <text>随访人数</text>
            <text>{{ StatisticItem.arcNum }}</text>
          </view>
          <view class="Statistic-text text-style">
            <text>随访人次</text>
            <text>{{ StatisticItem.arc_num }}</text>
          </view>
<!--          <view class="Statistic-text text-style">
            <text>续约人数</text>
            <text>{{ StatisticItem.TSign }}</text>
          </view> -->
          <view class="Statistic-text text-style">
            <text>体检人数</text>
            <text>{{ StatisticItem.checkNum }}</text>
          </view>
          <view class="Statistic-text text-style">
            <text>体检人次</text>
            <text>{{ StatisticItem.check_num }}</text>
          </view>
        </view>
      </view>
      </scroll-view>
     </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { computed } from 'vue'
import { onLoad, onShow, onTabItemTap } from '@dcloudio/uni-app'
import { http } from '@/utils/http'
  const StatisticV = ref({
    StatisticVList: []
  });

//跳转


const activeButton = ref('');
const dateRange = ref(['', '']);
const defaultStartDate = '2024-01-01';
const defaultEndDate = '2025-12-31';

const fetchYearData = () => {
  activeButton.value = 'year';
  const currentYear = new Date().getFullYear();
  dateRange.value = [`${currentYear}-01-01`, `${currentYear}-12-31`];
  getList();

};

const fetchMonthData = () => {
    activeButton.value = 'month';
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth() + 1;
    const daysInMonth = new Date(currentYear, currentMonth, 0).getDate();
    dateRange.value = [`${currentYear}-${currentMonth}-01`, `${currentYear}-${currentMonth}-${daysInMonth}`];
    getList();

};

const fetchWeekData = () => {
  activeButton.value = 'week';
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1;
  const currentDay = currentDate.getDate();
  const currentWeekDay = currentDate.getDay();
  const firstDayOfWeek = currentDay - currentWeekDay + 1;
  const lastDayOfWeek = firstDayOfWeek + 6;
  dateRange.value = [`${currentYear}-${currentMonth}-${firstDayOfWeek}`, `${currentYear}-${currentMonth}-${lastDayOfWeek}`];

  getList();

};

const fetchDayData = () => {
    activeButton.value = 'day';
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth() + 1;
    const currentDay = currentDate.getDate();
    dateRange.value = [`${currentYear}-${currentMonth}-${currentDay}`, `${currentYear}-${currentMonth}-${currentDay}`];

    getList();

};

const toDetail = (StatisticItem) => {
uni.navigateTo({ url: `/pages/staDetail/staDetail?crowdName=${encodeURIComponent(StatisticItem.name)}` });
}

const getList = () => {
  http({
    url: '/crowd/getAllCrowd',
    method: 'GET',
  }).then(response => {
    if (response.code === 200 && response.data) {
      const updates = response.data.map(item => ({
        name: item.crowdName,
        dNum: 0, // 默认值
        signnum: 0,
        TSign: 0,
        checkNum: 0,
        check_num: 0
      }));

      // 更新StatisticVList
      StatisticV.value.StatisticVList = updates;

      updates.forEach((item, index) => {
        http({
          url: `/patient/count?diseaseName=${item.name}&startingTime=${dateRange.value[0]}&endingTime=${dateRange.value[1]}`,
          method: 'GET',
        }).then(countResponse => {
          if (countResponse.code === 200 && countResponse.data) {
            StatisticV.value.StatisticVList[index] = {
              ...StatisticV.value.StatisticVList[index],
              dNum: countResponse.data['建档人数'],
              signnum: countResponse.data['签约人数'],
              //TSign: countResponse.data['体检人数'],
              checkNum: countResponse.data['体检人数'],
              check_num: countResponse.data['体检人次'],
              arcNum: countResponse.data['随访人数'],
              arc_num: countResponse.data['随访人次']
            };
          }
        }).catch(error => {
          console.error(`请求 /patient/count?diseaseName=${item.name} 出错:`, error);
        });
      });
    }
  }).catch(error => {
    console.error('请求 /crowd/getAllCrowd 出错:', error);
  });
};


  const dividedStatisticList = computed(() => {
    const list = StatisticV.value.StatisticVList;
    const rows = [];
    for (let i = 0; i < list.length; i += 5) {
      rows.push(list.slice(i, i + 5));
    }
    return rows;
  });

const onDateRangeChange = () => {
  getList();
};
  onLoad(() => {
    //getList();
    fetchYearData();
  })
</script>

<style scoped lang="scss">
.statistics{
  padding: 10rpx 5rpx 0 5rpx;
  position: relative;
}
//日期
  .sta-header {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 5rpx;
    background-color: #fff;
    font-size: 16px;
  }



  .time-button {
    padding: 5rpx 10rpx;
    margin: 0 5rpx;
    background-color: #ffffff;
    border: none;
    border-radius: 5rpx;
    font-size: 16px;
  }

.time-button.active {
  color: #00aaff;
}

.date-header{
  width: 30%;

}


  .list-container {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: center;
      padding: 10px;
      background-color: #f0f0f0;
      width: 100%;
      height: calc(100vh - 110rpx);;
      overflow-y: auto;

//列表
      .Statistic-item {
        position: relative;
        display: flex;
        justify-content: space-around;
        align-items: center;
        background-color: #fefefe;
        height: 80rpx;
        overflow: hidden;
        margin-bottom: 4rpx;
      }
      .list-name {
        position: absolute;
        top: 15px;
        left: 15px;

        z-index: 10;
      }

      .Statistic-text {
        font-size: 16px;
      }
      .text-style {
        display: flex;
        margin-top: 35px;
        flex-direction: column;
        align-items: flex-start;
      }

  }




</style>
